package com.thd.springboot.framework.utils;


import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * com.thd.base64.MyBase64Utils
 *
 * @author: wanglei62
 * @DATE: 2022/10/11 10:36
 **/
public class MyBase64Utils {
    /**
     * 将字符串编码成base64字符串
     * @param str
     * @return
     */
    public static String encodeStr(String str){
        //base64加密
        byte[] b = str.getBytes();
        Base64 base64 = new Base64();
        b = base64.encode(b);
        String s = new String(b);
        return s;
    }

    /**
     * 将base64字符串解码为字符串
     * @param str
     * @return
     */
    public static String decodeStr(String str){
        //base64解密
        byte[] b = str.getBytes();
        Base64 base64 = new Base64();
        b = base64.decode(b);
        String s = new String(b);
        return s;
    }

    public static String encodeFile(String filePath) throws Exception{
        //base64加密
        Base64 base64 = new Base64();
        File f = new File(filePath);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream input = new FileInputStream(f);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = input.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }

        String result = base64.encodeToString(baos.toByteArray());
        baos.close();
        return result;
    }


    public static void decodeFile(String base64Str,String filePath) throws Exception {

        File f = new File(filePath);
        if(f.exists()){
            throw new RuntimeException("File is existed");
        }


        Base64 base64 = new Base64();
        byte[] bytes = base64.decode(base64Str.getBytes(StandardCharsets.UTF_8));
        OutputStream os = new FileOutputStream(f);
        os.write(bytes);
        os.close();

    }


}
